package com.server.questionbank.snframe.controller.Course;

import com.server.questionbank.snframe.controller.Course.pojo.FindCourse;
import com.server.questionbank.snframe.domain.Course.*;
import com.server.questionbank.snframe.domain.Course.Chapter.TChapter;
import com.server.questionbank.snframe.domain.Course.Chapter.TLessons;
import com.server.questionbank.snframe.domain.Course.Result.RCourseComment;
import com.server.questionbank.snframe.domain.Course.Result.CourseDetails;
import com.server.questionbank.snframe.domain.Course.Result.CourseResourceInfo;
import com.server.questionbank.snframe.domain.Course.Result.CourseTeacher;
import com.server.questionbank.snframe.domain.Course.Result.CourseFigures;
import com.server.questionbank.snframe.domain.Course.Type.CourseDifficulty;
import com.server.questionbank.snframe.domain.Course.Type.CourseLabel;
import com.server.questionbank.snframe.domain.Course.Type.CourseType;
import com.server.questionbank.snframe.domain.QuestionBank.Knowledge;
import com.server.questionbank.snframe.domain.ResDTO.PageResult;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.domain.ResDTO.SearchResult;
import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.service.CourseService.*;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberService;
import com.server.questionbank.snframe.service.CourseService.Resource.CourseResourceService;
import com.server.questionbank.snframe.service.TCollectionService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.MinIo.MinIoBucket;
import com.server.questionbank.snframe.util.MinIo.MinIoFactory;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/course/overt")
public class CourseOvertController {
    @Autowired // 课程服务
    private TCourseService tCourseService;
    @Autowired // 课程类型服务
    private CourseTypeService courseTypeService;
    @Autowired // 用户服务
    private UsersService usersService;
    @Autowired // 知识点服务
    private TKnowledgeService tKnowledgeService;

    @Autowired // 课程文件服务
    private CourseResourceService courseResourceService;

    @Autowired // 章节服务
    private TChapterService tChapterService;

    @Autowired // minio 工厂
    MinIoFactory minIoFactory;

    @Autowired
    private CourseCommentService courseCommentService;

    @Autowired // 学生服务
    private CusMemberService cusStudyService;

    @Autowired
    private TCollectionService  tCollectionService;

    // 获取课程
    @PostMapping("/findCourse")
    public ResponseResult<SearchResult<PageResult<CourseFigures>>> findCourse(@RequestBody FindCourse findCourse) {
        try {
            return ResponseResult.success(tCourseService.findCourseByConditions(
                    findCourse.getCourseId(), null, findCourse.getCourseName(), findCourse.getCourseDifficulty(), findCourse.getCourseType(), findCourse.getCourseLabel(),
                    null, findCourse.getPageNum(), findCourse.getPageSize(), true
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("查询失败");
        }
    }

    // 获取热门课程
    @PostMapping("/findHotCourse")
    public ResponseResult<List<CourseFigures>> findHotCourse(){
        try {
            return ResponseResult.success(tCourseService.getHotCourse());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("查询失败");
        }
    }

    // 获取课程信息
    @PostMapping("/findCourseInfo")
    public ResponseResult<CourseDetails> findCourseInfo(@RequestBody Map<String, Long> map){
        CourseDetails  courseDetails = new CourseDetails();
        try {
            // 获取课程信息
            TCourse tCourse = tCourseService.getCourseById(map.get("courseId"));
            if (tCourse == null) return ResponseResult.error("课程不存在");
            courseDetails.setCourseInfo(tCourse);
            // 获取课程统计信息
            CourseFigures resultFindCourse = tCourseService.findCourseByConditions(
                    tCourse.getCourseId(), null,
                    null, null, null, null, null,
                    1L, 1L, false).getData().getList().get(0);
            courseDetails.setCourseFigures(resultFindCourse);
            // 获取教师信息
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setTeacher(usersService.selectUserById(tCourse.getCreateBy()));

            // 获取收藏
            TUser user = usersService.getLoginUser();
            if(user == null) courseDetails.setCollect(false);
            else courseDetails.setCollect(tCollectionService.selectCollection(user.getUserId(),  tCourse.getCourseId(), "course") != null);

            // 详细信息
            if(map.get("detailed") != null && map.get("detailed") > 0)
            {
                // 获取老师课程数量
                courseTeacher.setCourseCount(usersService.getCourseCount(tCourse.getCreateBy()));
                // 获取老师学生数量
                courseTeacher.setStudentCount(usersService.getStudentCount(tCourse.getCreateBy()));
                // 获取老师其他课程
                courseTeacher.setCourseList(tCourseService.findCourseByConditions(
                        null, tCourse.getCreateBy(),
                        null, null, null, null, tCourse.getCourseId() != null ? List.of(tCourse.getCourseId()) : null,
                        1L, 10L, false).getData().getList().stream() // 获取老师其他课程 (只获取前10个)
                        .map(CourseFigures::getCourseId)
                        .toList());
                // 获取课程难度
                List<CourseDifficulty> courseDifficulty = courseTypeService.getCourseDifficulty(tCourse.getCourseDifficultyId());
                if (courseDifficulty != null && courseDifficulty.size() > 0)
                    courseDetails.setCourseDifficulty(courseDifficulty.get(0));
                // 获取课程类型
                courseDetails.setCourseType(tCourseService.getCourseType(tCourse.getCourseId()));
                // 获取课程标签
                courseDetails.setCourseLabel(tCourseService.getCourseLabel(tCourse.getCourseId()));
                // 获取推荐课程
                courseDetails.setRecommendCourse(tCourseService.getRecommendCourse(tCourse.getCourseId(), 30L).stream().map(CourseFigures::getCourseId).toList());
            }

            // 设置教师信息
            courseDetails.setCourseTeacher(courseTeacher);
        } catch (Exception e)
        {
            e.printStackTrace();
            return ResponseResult.error("查询失败");
        }
        return ResponseResult.success(courseDetails);
    }

    // 获取课程类型
    @PostMapping("/findCourseType")
    public ResponseResult<List<CourseType>> findCourseType(@RequestBody Map<String, Long> map){
        return ResponseResult.success(tCourseService.getCourseType(map.get("courseId")));
    }

    // 获取课程标签
    @PostMapping("/findCourseLabel")
    public ResponseResult<List<CourseLabel>> findCourseLabel(@RequestBody Map<String, Long> map){
        return ResponseResult.success(tCourseService.getCourseLabel(map.get("courseId")));
    }

    // 获取课程介绍
    @PostMapping("/getIntroduceText")
    public ResponseResult<String> getCourseIntroduce(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(tCourseService.getCourseIntroduce(map.get("courseId")));
    }

    // 获取课程资源列表
    @PostMapping("/getResourceList")
    public ResponseResult<List<CourseResourceInfo>> getResourceList(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(courseResourceService.getResourceList(map.get("courseId")));
    }

    // 获取课程封面
    @GetMapping("/cover")
    @ApiOperation("课程封面")
    public void previewCover(@RequestParam("courseId") Long courseId, HttpServletResponse response) throws Exception {
        TCourse course = tCourseService.getCourseById(courseId);
        if (course == null) {
            response.setStatus(404);
            return;
        }
        String courseCoverPath = course.getCourseId() + "/cover/" + course.getCourseCover();
        if (courseCoverPath == null || courseCoverPath.isEmpty()) {
            response.setStatus(404);
            return;
        }
        MinIoBucket minIoBucket = minIoFactory.openBucket("course");
        try (InputStream inputStream = minIoBucket.downloadFile(courseCoverPath)) {
            String contentType = minIoBucket.getFileType(courseCoverPath);
            response.setContentType(contentType);
            IOUtils.copy(inputStream, response.getOutputStream());
        } catch (Exception e)
        {
            response.setStatus(404);
        }
    }

    // 获取课程评论列表
    @PostMapping("/getCourseComment")
    public ResponseResult<List<RCourseComment>> getCourseComment(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(courseCommentService.selectCourseCommentByCourseId(map.get("courseId")));
    }

    // 获取章节列表
    @PostMapping("/getChapterList")
    public ResponseResult<List<TChapter>> getChapterList(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(tChapterService.getChapterList(map.get("courseId")));
    }

    // 获取章节信息
    @PostMapping("/getChapterInfo")
    public ResponseResult<TChapter> getChapterInfo(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(tChapterService.getChapterInfo(map.get("chapterId")));
    }

    // 获取课时列表
    @PostMapping("/getLessonList")
    public ResponseResult<List<TLessons>> getLessonList(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(tChapterService.getLessonList(map.get("chapterId")));
    }

    // 获取课时信息
    @PostMapping("/getLessonInfo")
    public ResponseResult<TLessons> getLessonInfo(@RequestBody Map<String, Long> map) {
        return ResponseResult.success(tChapterService.getLessonInfo(map.get("lessonsId")));
    }

    // 获取知识点
    @PostMapping("/getKnowledges")
    public ResponseResult<List<Knowledge>> getKnowledges(@RequestBody Map<String, Long> map) {
        List<Knowledge> knowledgeList;
        try {
            if (map.get("chapterId") == null)
                knowledgeList = tKnowledgeService.getKnowledgeByCourseId(map.get("courseId"));
            else knowledgeList = tKnowledgeService.getKnowledgeByCameraId(map.get("chapterId"));
            return ResponseResult.success(knowledgeList);
        } catch (Exception e)
        {
            e.printStackTrace();
            return ResponseResult.error("获取知识点失败!");
        }
    }
}
